<?php


namespace App\Traits;

use Illuminate\Database\Eloquent\Model;

trait  FillData
{

    public function __construct(array $data=[])
    {
        $this->fill($data);
    }

    public function fill($data){
        $ref = new \ReflectionClass(static::class);
        $vars = $ref->getProperties();

        foreach ($vars as $temp){
            isset($data[$temp->name]) && $this->{$temp->name} = $data[$temp->name];
        }
    }

    public static function fromItem(array $data):self {
       return new static($data);
    }

    public static function fromList(array $list):array {
        $data = [];
        foreach ($list as $item){
            if($item instanceof Model){
                $data[] = new static($item->toArray());
            }else if(is_array($item)){
                $data[] = new static($item);
            }else{
                throw new \TypeError();
            }
        }
        return $data;
    }

    public function toArray()
    {
        return json_decode($this->toJson(),1);
    }

    public function toJson()
    {
        return json_encode($this);
    }

}
